<template>
  <el-dialog
    :title="showStatus === 1 ? '上传' : showStatus === 2 ? '支付费用' : '操作确认'"
    :visible.sync="dialogVisible"
    lock-scroll
    width="420px"
    @close="hide"
  >
    <div style="width: 100%; height: 219px">
      <div v-show="showStatus === 1">
        <div style="display: flex; align-items: center; justify-content: center; padding: 38px 0 43px">
          <div style="max-width: 114px" v-html="codeType === 'payment' ? '请上传您的<br>收款码' : '请上传您的<br>小程序商城二维码'"></div>
          <div style="display: flex; flex-wrap: wrap">
            <div style="position: relative" class="attachment_view" v-for="(item, index) in attachments" :key="index">
              <el-image
                style="width: 100%; height: 100%; border-radius: 3px"
                :src="item"
                :preview-src-list="attachments"
              >
              </el-image>
              <div class="attachment_mask">
                <img src="@/assets/att_del.png" style="width: 100%; height: 100%" @click="delAttachment(index)" />
              </div>
              <div class="attachment_mask_pre">
                <img src="@/assets/att_pre_y.png" />
              </div>
            </div>
            <!-- v-if="!maskViewStatus" -->
            <el-upload
              v-if="attachments.length < 1"
              class="uploader"
              :action="uploadAction"
              :on-success="handleSuccess"
              :headers="headers"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :data="{type:codeType === 'payment' ? 1 : 2,accountBookId:accountBookId}"
              list-type="picture"
            >
              <i slot="default" class="el-icon-plus"></i>
              <!-- <img src="@/assets/att_add.png" style="width: 100%; height: 100%" /> -->
              
            </el-upload>
            <!-- <div v-else-if="attachments.length < 1" class="uploader" style="cursor: no-drop;">
                  <img src="@/assets/att_add.png" style="width: 100%; height: 100%" />
                </div> -->
          </div>
        </div>
        <div slot="footer" class="dialog-footer">
          <button class="btn" @click="hide">取 消</button>
          <button
            :disabled="attachments.length < 1"
            @click="onSubmit()"
            style="margin-left: 17px"
            class="btn"
            :class="attachments.length < 1 && codeStatus !== 'error' ? 'disabled-btn' : 'btn-primary'"
          >
            {{ codeStatus === 'other' ? '支付' : '确认' }}
          </button>
        </div>
      </div>
      <div v-show="showStatus === 2">
        <div style="display: flex; justify-content: space-between; align-items: center; padding: 40px 60px 0">
          <div>
            <div style="font-weight: 400; font-size: 14px; color: #666666; line-height: 24px">{{codeType === 'payment' ? '显示收款码费用' : '显示小程序商城二维码费用'}}</div>
            <div style="font-weight: bold; font-size: 16px; color: #fd6c21; margin-top: 19px">
              <span style="font-size: 24px">{{ byModuleInfo.price }}元</span>/年
            </div>
          </div>
          <div>
            <div style="width: 97px; height: 97px; background: #fd6c21">
              <!-- <div style="margin: 0 auto" id="qrcode1" ref="qrCodeUrl1"></div> -->
              <vue-qr  :logoSrc="logoSrc" :text="signUrl" :size="97" :margin="0" :logoScale="0.26" :logoMargin="1" :correctLevel="3"></vue-qr>
            </div>
            <div style="text-align: center; margin-top: 10px">请扫码支付</div>
          </div>
        </div>
      </div>
      <div v-show="showStatus === 3">
        <div style="display: flex; align-items: center; justify-content: center; padding: 42px 0 50px">
          <!-- <img src="@assets/template.png" style="width: 42px; height: 42px" /> -->
          <i class="el-icon-success" style="font-size: 42px; color: #52c41a"></i>
          <div style="font-size: 12px; margin-left: 32px">您已购买成功。</div>
        </div>
        <div slot="footer" class="dialog-footer" style="margin-left: 42px">
          <button @click="hide" class="btn btn-primary">确定</button>
          <button class="btn" @click="hide" style="margin-left: 17px">取 消</button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import logoSrc from "@/assets/logo.png";
// import QRCode from 'qrcodejs2'
import VueQr from 'vue-qr'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID, USER_INFO, ACCOUNT_BOOK,SAMPLE_FLAG } from '@/store/mutation-types'
import { getAction,postAction } from '../../api/manage'


export default {
    components: {VueQr},
  data() {
    return {
        logoSrc,
      dialogTitle: '上传',
      codeType:'',
      codeStatus:'',
      showStatus: 1,
      dialogVisible: false,
      attachments: [],
      //   uploadAction: window._CONFIG['domianURL'] + '/sys/common/upload',
      uploadAction: window._CONFIG['domianURL'] + '/sys/common/uploadQrCode',
      headers: { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN),'Xgh-Experience-User' : Vue.ls.get(SAMPLE_FLAG) == 1 ? 'new' : 'old' },
      payText: true,
      orderInfo: {},
      orderNumber:'',
      byModuleInfo:{},
      signUrl:'',
      accountBookId: Vue.ls.get(ACCOUNT_BOOK).id,
      timer: null,
    }
  },
  methods: {
    onSubmit() {
      console.log('eeeeeeeeee', this.payText)
      // attachment: this.attachments.join(','),
      if (this.codeStatus === 'other') {
        console.log('支付', this.orderInfo)
        
        getAction('/xghModulePrice/xghModulePrice/queryByModuleNumber', {moduleNumber:this.codeType === 'payment' ? 'SKMFXZS' : 'XCXSCEWMZS'}).then((res) => {
            console.log("获取价格",res)
            if (res.success) {
              this.byModuleInfo = res.result
              this.handleAddOrder()
            } else {
              this.$elMessage.error(res.message)
            }
          })
        
        // 支付
            // postAction('/xghShareOrderPaymentOrders/xghShareOrderPaymentOrders/add', {accountBookId,...this.orderInfo}).then((res) => {
            // console.log(res)
            // if (res.success) {
            //   let result = res.result || {}
            //   this.buyInfo = {
            //     ...result,
            //     title: '使用模板',
            //     showType: result.freeCountUsage > 0 ? 1 : 2,
            //     haveFree: result.freeCount > 0,
            //     visible: true,
            //   } //showType 1(有免费次数) 2（购买）3（购买成功）
            //   //haveFree 是否有免费使用个数

            //   //没有免费次数先生成订单用于生成支付二维码
            //   if (result.freeCount == 0 || result.freeCountUsage == 0) {
            //     this.handleAddOrder(1)
            //   }
        //     } else {
        //       this.$elMessage.error(res.message)
        //     }
        //   })
      }else{
        this.$emit('uploadImg',this.codeType,this.attachments)
        this.hide()
      }
    },
    handleAddOrder() {
      // let accountBookId = Vue.ls.get(ACCOUNT_BOOK).id

      //buyType 1已买 2未买
      let params = {
        xghAccountBookId:this.accountBookId,
        goodsId:this.byModuleInfo.id,
        goodsType:this.codeType === 'payment' ? 8 : 9,
        goodsName:this.byModuleInfo.moduleName,
        goodsNumber:1,
        moduleNumber:this.byModuleInfo.moduleNumber,
        buyType:this.byModuleInfo.buyType,
        orderMoney: this.byModuleInfo.price,
        // ...this.orderInfo,
      }
      console.log(params)

      postAction('/XghAuthorizationCenter/xghAuthorizationCenterOrders/add', params).then((res) => {
        if (res.code == 200) {
          console.log("添加订单成功",res)
          this.orderNumber = res.result.orderNumber
          this.confirmPay()
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    confirmPay() {
      // 微信支付配置的是晓光的服务，没有配郭哥的，正式用晓光的。
      //
      this.signUrl = `http://cloudjinxiaocun.good-software.cn/#/?orderNumber=${this.orderNumber}`
      // 本地 环境
      // let signUrl = `http://192.168.2.24:9002/#/?orderNumber=${this.orderModel.orderNumber}`
      // this.signUrl = `http://192.168.0.181:9002/#/?orderNumber=${this.orderNumber}`
      console.log("this.signUrl",this.signUrl)


      this.showStatus = 2
    //   document.getElementById('qrcode1').innerHTML = ''
    //   var qrcode = new QRCode(this.$refs.qrCodeUrl1, {
    //     text: signUrl,
    //     width: 97,
    //     height: 97,
    //     colorDark: '#333333', //二维码颜色
    //     colorLight: '#ffffff', //二维码背景色
    //     correctLevel: QRCode.CorrectLevel.H,
    //   })
      
      this.checkInterval()
    },
    handleBuyCancel() {
      this.buyInfo.visible = false
      if (this.timer) {
        clearInterval(this.timer)
      }
    },
    checkInterval() {
      this.timer = setInterval(() => {
        this.checkTimeOut(this.timer)
      }, 5000)
    },
    checkTimeOut(timer) {
      const that = this
      setTimeout(() => {
        getAction('/pay/query', { orderNumber: that.orderNumber }).then((res) => {
          console.log('查询支付结果', res)
          if (res.success) {
            clearInterval(timer)
            this.$emit('uploadImg',this.codeType,this.attachments)
            this.showStatus = 3
            // that.showSignModal = false
            // let model = res.result[0]
            // if (model.goodsType == 7) {
            //   that.paySuccess()
            // }
          }
        })
      }, 0)
    },
    show(code,status) {
      console.log("code",code,"status",status)
      this.showStatus = 1
      this.codeType = code
      this.codeStatus = status
      this.dialogVisible = true
      // let accountBookId = Vue.ls.get(ACCOUNT_BOOK).id
      // let signUrl = `https://yun.xiangguohe.cn?from=share&accountBookId=${accountBookId}&${params}`
      // console.log(signUrl)
      
    },
    hide() {
      this.dialogVisible = false
      this.showStatus = 1
      this.attachments = []
      if (this.timer) {
        clearInterval(this.timer)
      }
    },
    beforeUpload(file) {
      console.log(123456, file)

      let type = file.type.toLowerCase()
      const isJPG = type.includes('png') || type.includes('jpeg') || type.includes('jpg')
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('请上传png/jpg/jpeg格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleSuccess(e) {
      console.log(123456, e)
      if (e.code === 200) {
        this.attachments.push(e.message)
        this.codeStatus = 'our'
        // if (this.attachments.length < 5) {
        //   this.attachments.push(e.message)
        // } else {
        //   this.$message.error('最多支持上传5张!')
        // }
      } else if (e.code === 500) {
        // 不是二维码图片
        // this.attachments.push(e.message)
        this.$message.error(e.message)
        // this.codeStatus = 'error'

      } else if (e.code === 501) {
        this.attachments.push(e.message)
        // this.$message.error(e.message)
        this.codeStatus = 'other'
      }
      else {
        this.$message.error(e.message)
      }
    },
    delAttachment(index) {
      this.attachments.splice(index, 1)
    },
  },
}
</script>

<style lang="scss" scoped>
.btn {
  width: 60px;
  height: 30px;
  border: none;
  border-radius: 5px 5px 5px 5px;
  border-width: 1px;
  border-style: solid;
  background: #fff;
  border-color: #dddddd;
  cursor: pointer;
}

.btn-primary {
  background: #1993fb;
  border-color: #1993fb;
  color: #fff;
}

.disabled-btn {
  border-color: #999999;
  background: #999999;
  color: #fff;
  cursor: not-allowed;
}

::v-deep .el-dialog__header {
  border-bottom: 1px solid #eeeeee;
  padding: 15px 13px 23px 18px;
}

::v-deep .el-dialog__body {
  padding: 0;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: center;
}

.uploader {
  position: relative;
  overflow: hidden;
  width: 52px;
  height: 52px;
  margin-left: 17px;
  background-color: #bebebe;
  display: flex;
  justify-content: center;
  align-items: center;

  .el-icon-plus {
    color: #fff;
    font-size: 20px;
    font-weight: bold;
  }
}

.attachment_view {
  border: 1px dashed white;
  width: 68px;
  height: 68px;
  margin-left: 17px;
  background-color: #f6f6f6;
  line-height: 40px;
  text-align: center;
  border-radius: 3px;
}

.attachment_mask {
  z-index: 2;
  position: absolute;
  right: 0;
  top: 0;
  width: 12px;
  height: 12px;
  display: flex;
  align-items: center;
}

.attachment_mask_pre {
  z-index: 1;
  position: absolute;
  display: flex;
  align-items: center;
  pointer-events: none;
  right: 0;
  top: 0;
  left: 0;
  bottom: 0;
  backdrop-filter: blur(0.5px);

  img {
    position: absolute;
    width: 24px;
    height: 24px;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
  }
}
</style>